package com.linx.rxdata

import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject

class RxListData<T>(private val list: MutableList<T>) : RxCollectionData<T>(list), MutableList<T> {

    private val subject = BehaviorSubject.create<List<T>>().also {
        it.onNext(this)
    }

    override fun observe(): Observable<List<T>> {
        return subject
    }

    override fun emit() {
        subject.onNext(this)
    }

    override fun add(index: Int, element: T) {
        wrap {
            list.add(index, element)
            true
        }
    }

    override fun removeAt(index: Int): T {
        return wrap {
            list.removeAt(index)
        }
    }

    override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> {
        return RxListData(list.subList(fromIndex, toIndex)).also {
            it.observe()
                    .subscribe {
                        subject.onNext(this)
                    }
        }
    }

    override fun addAll(index: Int, elements: Collection<T>): Boolean {
        return wrap {
            list.addAll(index, elements)
        }
    }

    override fun set(index: Int, element: T): T {
        return wrap {
            list.set(index, element)
        }
    }

    override fun get(index: Int): T {
        return list[index]
    }

    override fun indexOf(element: T): Int {
        return list.indexOf(element)
    }

    override fun lastIndexOf(element: T): Int {
        return list.lastIndexOf(element)
    }

    override fun listIterator(): MutableListIterator<T> {
        return list.listIterator()
    }

    override fun listIterator(index: Int): MutableListIterator<T> {
        return list.listIterator(index)
    }

}